package com.util.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Description: TODO
 * @Author: hechaobo
 * @Date: 2024/9/4
 **/
@Slf4j
public class FtpUtil {

    public static void pull(String server, int port, String username, String password,
                            String localFilePath, String remoteFilePath) {
        FTPClient ftpClient = new FTPClient();

        try {
            // 连接FTP服务器
            ftpClient.connect(server, port);
            ftpClient.login(username, password);

            // 设置文件传输模式为二进制，以防止文本模式的自动转换问题
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            // 检查是否成功登录
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("FTP服务器拒绝连接。");
                return;
            }

            // 下载文件
            OutputStream outputStream = new FileOutputStream(localFilePath);
            boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);
            outputStream.close();

            if (success) {
                System.out.println("文件下载成功！");
            } else {
                System.out.println("文件下载失败！");
            }

        } catch (IOException e) {
            log.error("{}", e);
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                log.error("{}", e);
            }
        }
    }
}
